<?php

/**
 * 运行应用程序
 * @since 1.0.0 2013-9-12 by sutroon
 */
function App_Run()
{

    // 获取脚本文件(模块)名称，默认IndexAction.class.php,可以通过Api/Api_ShoppingCarAction.class.php来获取分组模块
    $modulename = get_module_name() . 'Action';
    // 获取操作方法名称，默认index
    $actionname = get_action_name();

    //根据$action参数调用不同的代码文件，从而满足单一入口实现对应的不同的功能
    if (strpos($modulename, '/'))
    {
        global $SO_LIB_DIR;
        $arrmodulename = explode('/', $modulename);
        $modulename = $arrmodulename[1];
        $scriptpath = $SO_LIB_DIR[strtoupper($arrmodulename[0])] . $modulename . '.class.php';
    } else
    {
        if (defined('SINTLE_PAGE_MODE') && SINTLE_PAGE_MODE)
        {
            $modulename = 'IndexAction'; // 2014-3-17 新增单页模式框架模式
        }
        $scriptpath = SITE_PATH . $modulename . '.class.php';
    }
    if (is_file($scriptpath))
    {
        include($scriptpath);
        APP_Exec($modulename, $actionname);
    } else
    {
        write_log('页面未找到:' . $scriptpath, true);
        echo 'Sorry, the file is not found :(<br />Back to <a href="?m=Index">Home</a>.';
    }
    unset($app_modules);
}

/**
 * 执行指定类的指定方法
 * @param type $classname
 * @param type $actionname
 * @since 1.0.0 sutroon 2013-9-12
 */
function App_Exec($classname, $actionname)
{
    try
    {
        $class = new ReflectionClass($classname);
        if (!$class->hasMethod($actionname))
            exit('ACTION NOT FOUND!' .$classname.'.'. $actionname . '<br />Back to <a href="?m=Index">Home</a>.');
        $method = $class->getMethod($actionname);
        if (!$method->isPublic())
            exit('ACTION IS NOT PUBLIC.' .$classname.'.' . $actionname . '<br />Back to <a href="?m=Index">Home</a>.');
        $obj = $class->newInstance();
        $method->invoke($obj);
        // URL参数绑定检测
        /* if($method->getNumberOfParameters()>0){
          switch($_SERVER['REQUEST_METHOD']) {
          case 'POST':
          $vars    =  array_merge($_GET,$_POST);
          break;
          case 'PUT':
          parse_str(file_get_contents('php://input'), $vars);
          break;
          default:
          $vars  =  $_GET;
          }
          $params =  $method->getParameters();
          foreach ($params as $param){
          $name = $param->getName();
          if(isset($vars[$name])) {
          $args[] =  $vars[$name];
          }elseif($param->isDefaultValueAvailable()){
          $args[] = $param->getDefaultValue();
          }else{
          throw new Exception('_PARAM ERROR_'.$name);
          }
          }
          $method->invokeArgs($obj,$args);
          }else{
          $method->invoke($obj);
          } */
    } catch (ReflectionException $e)
    {
        error_msg('Invoke Fail:' . $e->getMessage());
    }
}

/**
 * 获取变量的值 (Get、POST、COOKIE、SESSION)
 * @param string $name 变量的名称
 * @param numeric $defv 变量的默认值
 * @param string $querytype 值为GET|POST|COOKIE|SESSION|ALL
 * @return $MIX
 * @since 1.0.0 2013-9-17 sutroon
 */
function request_value($name, $defv = '', $querytype = 'ALL')
{
    switch ($querytype)
    {
        case 'GET':
            return isset($_GET[$name]) ? get_url_param($name) : $defv;
        case 'POST':
            return isset($_POST[$name]) ? $_POST[$name] : $defv;
        case 'COOKIE':
            return isset($_COOKIE[$name]) ? $_COOKIE[$name] : $defv;
        case 'SESSION':
            return isset($_SESSION[$name]) ? $_SESSION[$name] : $defv;
        default:
            if (isset($_GET[$name]))
                return get_url_param($name);
            if (isset($_POST[$name]))
                return $_POST[$name];
            if (isset($_COOKIE[$name]))
                return $_COOKIE[$name];
            if (isset($_SESSION[$name]))
                return $_SESSION[$name];
            return $defv;
    }
}

/**
 * 获取变量的数字值 (Get、POST、COOKIE、SESSION)
 * @param string $name 变量的名称
 * @param numeric $defv 变量的默认值
 * @param string $querytype 值为GET|POST|COOKIE|SESSION|ALL
 * @return numeric
 * @since 1.0.0 2013-9-17 sutroon
 */
function request_numeric($name, $defv = 0, $querytype = 'ALL')
{
    $v = request_value($name, $defv, $querytype);
    return is_numeric($v) ? $v : $defv;
}

/**
 * 获取变量的字符串值 (Get、POST、COOKIE、SESSION)
 * @param string $name 变量的名称
 * @param numeric $defv 变量的默认值
 * @param string $querytype 值为GET|POST|COOKIE|SESSION|ALL
 * @return string
 * @since 1.0.0 2013-9-17 sutroon
 */
function request_string($name, $defv = '', $querytype = 'ALL')
{
    $v = request_value($name, $defv, $querytype);
    return is_array($v) ? $v : mysql_real_escape_string($v);
}

/**
 * 跳转到指定地址
 * @param type $msg
 * @param type $url
 * @param type $time
 */
function redirect($msg, $url = '', $time = 3)
{
    if ($url)
    {
        if (defined('URL_Suffix') && !end_with($url, URL_Suffix))
            $url = $url . URL_Suffix;
    }else
    {
        $url = '?' . $_SERVER['QUERY_STRING'];
    }
    if ($msg)
    {
        echo "<div style='font-size:14px; line-height:21px; padding:10px;'>$msg<br /><span id='panCountDown'>$time</span>秒后即将 <a href='$url'>[跳转]</a> ...</div>";
        echo "<script type='text/javascript'>var i=$time;var timer=setInterval(function(){{i--;document.getElementById('panCountDown').innerHTML=i;if(i==0){{location.href='$url';clearInterval(timer)}}}},1000);</script>";
    } else
    {
        header('Location:' . $url);
    }
    exit();
}

/**
 * 获取Uri信息
 * @param type $type
 * @return type
 * @since 1.0.0 2013-4-13 sutroon
 */
function get_url($type = 'ALL')
{
    $protocol = strpos(strtolower($_SERVER['SERVER_PROTOCOL']), 'https') === FALSE ? 'http' : 'https';
    $host = $_SERVER['HTTP_HOST'];
    $port = $_SERVER["SERVER_PORT"];
    $script = $_SERVER['SCRIPT_NAME'];
    $query = $_SERVER['QUERY_STRING'];
    if ($query)
        $query = '?' . $query;
    $port = $port == '80' ? '' : ':' . $port;
    switch (strtolower($type))
    {
        case 'domain':
            return $protocol . '://' . $host;
        case 'scriptfile':
            return $protocol . '://' . $host . $script;
        case 'scriptandquery':
            return $script . $query;
        default:
            return $protocol . '://' . $host . $port . $script . $query;
    }
}

/**
 * 替换url参数
 * @param type $arrparams
 * @since 1.0.0 2013-9-30 sutroon
 * @example set_url_param(array('page'=>1));
 */
function set_url_param($arrparams)
{
    $query = trim_url_suffix($_SERVER['QUERY_STRING']);
    parse_str($query, $arr);
    foreach ($arrparams as $k => $v)
        $arr[$k] = $v;
    $query = http_build_query($arr);
    return $query ? '?' . $query . (defined('URL_Suffix') ? URL_Suffix : '') : $query;
}

/**
 * 获取url参数
 * 
 * @param type $name
 * @return type
 * @since 1.0.0 2013-10-7 sutroon
 * @example get_url_param('id');
 */
function get_url_param($name)
{
    $query = trim_url_suffix($_SERVER['QUERY_STRING']);
    parse_str($query, $arr);
    return $arr[$name];
}

function get_url_querystring($prefix = '?')
{
    $query = trim_url_suffix($_SERVER['QUERY_STRING']);
    parse_str($query, $arr);
    $str = $prefix;
    foreach ($arr as $n => $v)
    {
        $str.=$n . '=' . $v . '&';
    }
    if (strlen($str) > 1)
        $str = substr($str, 0, strlen($str) - 1);
    return $str;
}

function get_post_querystring()
{
    
}

/**
 * 获取url查询字符串中m的值
 * @return type
 * @since 1.0.0 2013-10-15 sutroon
 */
function get_module_name()
{
    return isset($_GET['m']) ? trim_url_suffix($_GET['m']) : 'Index';
}

/**
 * 获取url或post变量中action的值
 * @return type
 * @since 1.0.0 2013-10-15 sutroon
 */
function get_action_name()
{
    return isset($_REQUEST['action']) ? trim_url_suffix($_REQUEST['action']) : 'index';
}

/**
 * 从全局配置文件读取模板名称
 * @return type
 * @since 1.0.0 2014-1-19 sutroon
 */
function get_template_name($defv = 'default')
{
    return defined('TEMPLATE_NAME') ? strtolower(TEMPLATE_NAME) : $defv;
}

/**
 * 去除url后缀
 * @param type $str
 * @return type
 * @since 1.0.0 2013-10-7 sutroon
 */
function trim_url_suffix($str)
{
    return defined('URL_Suffix') && end_with($str, URL_Suffix) ? substr($str, 0, strlen($str) - strlen(URL_Suffix)) : $str;
}

/**
 * 自定义错误信息处理方法
 * @param type $errno
 * @param type $errstr
 * @param type $errfile
 * @param type $errline
 * @since 1.0.0 2013-10-8 sutroon
 */
function so_error_handler($errno, $errstr, $errfile, $errline)
{
    $errname = array_search($errno, array('E_ERROR' => 1, 'E_WARNING' => 2, 'E_PARSE' => 4, 'E_NOTICE' => 8));
    $msg = PHP_EOL . '出错代码：' . $errno . ' ' . $errname . ' [' . date('Y-m-d h:i:s') . ']' . PHP_EOL;
    $msg.='出错信息：' . $errstr . PHP_EOL;
    $msg.='出错地址:' . get_url() . ' IP:' . get_client_ip() . PHP_EOL;
    $msg.='出错文件：' . $errfile . ' 行：' . $errline . PHP_EOL;
    write_log($msg);
    error_msg('抱歉，系统出错咯...');
    // echo nl2br($msg);
    if ($errno == E_WARNING)
    {
        exit();
    }
}

/**
 * 将错误日志写入到文件
 * 
 * @param type $msg
 * @param bool $autoformat 是否自动生成格式化日志内容
 * @return boolean
 * @since 1.0.0 2013-10-8 sutroon
 */
function write_log($msg, $autoformat = false)
{
    if ($autoformat)
    {
        $str = PHP_EOL . '出错代码：CustomerError [' . date('Y-m-d h:i:s') . ']' . PHP_EOL;
        $str.='出错信息：' . $msg . PHP_EOL;
        $str.='出错地址:' . get_url() . ' IP:' . get_client_ip() . PHP_EOL;
        $msg = $str;
    }
    $logdir = SITE_PATH . 'Data/Log/';
    if (!is_dir($logdir))
        mkdir($logdir, 0700, true);
    $logname = date('Y_m_d');
    $logfile = $logdir . $logname . '.log';
    if (!file_exists($logfile))
    {
        file_put_contents($logfile, $msg);
        return true;
    }
    // 每个日志文件限制在500k,打开的速度比较快
    $maxfilesize = 500000;
    if (filesize($logfile) < $maxfilesize)
    {
        file_put_contents($logfile, $msg, FILE_APPEND);
        return true;
    }
    $i = 1;
    // 5GB
    while ($i < 10000)
    {
        $logfile = $logdir . $logname . '_' . $i . '.log';
        if (!file_exists($logfile) || filesize($logfile) < $maxfilesize)
        {
            break;
        }
        $i++;
    }
    file_put_contents($logfile, $msg, FILE_APPEND);
    return TRUE;
}

/**
 * 输出消息并终止后续输出
 * @param type $msg
 * @param type $exit
 */
function error_msg($msg, $exit = true)
{
    echo $msg . '<br />Back to <a href="?m=Index">Home</a>.';
    if ($exit)
    {
        exit();
    }
}

/**
 * 检测字符串是否已指定的字符串开头
 * @param type $str
 * @param type $search
 * @return boolean
 * @example start_with('this is my words','th');
 * @since 1.0.0 2013-10-7 sutroon
 */
function start_with($str, $search)
{
    if (strlen($str) < strlen($search))
    {  //若第一个字符串长度小于第二个的时候，必须指定返回false，
        return false;                                   //否则substr_compare遇到这种情况会返回0（即相当，与事实不符合）
    } else
    {
        return !substr_compare($str, $search, 0, strlen($search)); //当第一个长度大于第二个时才开始判断
    }
}

/**
 * 检测字符串是否已指定的字符串结尾
 * @param type $str
 * @param type $search
 * @return boolean
 * @example end_with('my words','ds');
 * @since 1.0.0 2013-10-7 sutroon
 */
function end_with($str, $search)
{
    if (strlen($str) < strlen($search))
    {  //若第一个字符串长度小于第二个的时候，必须指定返回false，
        return false;                                   //否则substr_compare遇到这种情况会返回0（即相当，与事实不符合）
    } else
    {
        return !substr_compare($str, $search, strlen($str) - strlen($search), strlen($search)); //从第一个字符串减去第二个字符串长度处开始判断
    }
}

/**
 * 判断是否是wap访问 
 * @since 1.0.0 2013-5-4 sutroon
 */
function is_wap()
{
    // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
    if (isset($_SERVER['HTTP_X_WAP_PROFILE']))
    {
        return true;
    }
    //如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
    if (isset($_SERVER['HTTP_VIA']))
    {
        if (stristr($_SERVER['HTTP_VIA'], 'wap'))
            return true;
    }
    //判断手机发送的客户端标志,兼容性有待提高
    if (isset($_SERVER['HTTP_USER_AGENT']))
    {
        // 从HTTP_USER_AGENT中查找手机浏览器的关键字
        $USER_AGENT = strtoupper(trim($_SERVER['HTTP_USER_AGENT']));
        if (strpos($USER_AGENT, 'WAP') > 0 || strpos($USER_AGENT, 'MOBILE') > 0 || strpos($USER_AGENT, 'NOKIA') > 0 || strpos($USER_AGENT, 'MIDP') > 0 || strpos($USER_AGENT, 'UCWEB') > 0)
        {
            return true;
        }
    }
    //协议法，因为有可能不准确，放到最后判断
    if (isset($_SERVER['HTTP_ACCEPT']))
    {
        // 如果只支持wml并且不支持html那一定是移动设备
        // 如果支持wml和html但是wml在html之前则是移动设备
        $HTTP_ACCEPT = strtoupper($_SERVER['HTTP_ACCEPT']);
        if (strpos($HTTP_ACCEPT, 'VND.WAP') > 0 || strpos($HTTP_ACCEPT, 'UC/') > 0)
        {
            return true;
        }
    }
    return false;
}

/**
 * 获取客户端IP地址
 * 0=ip地址,1=ipv4地址数字
 * 
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @return mixed
 * @since 1.0.0 2013-5-10 sutroon
 */
function get_client_ip($type = 0)
{
    $type = $type ? 1 : 0;
    static $ip = NULL;
    if ($ip !== NULL)
    {
        return $ip[$type];
    }
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
    {
        $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $pos = array_search('unknown', $arr);
        if (false !== $pos)
        {
            unset($arr[$pos]);
        }
        $ip = trim($arr[0]);
    } elseif (isset($_SERVER['HTTP_CLIENT_IP']))
    {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (isset($_SERVER['REMOTE_ADDR']))
    {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u", ip2long($ip));
    $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}

/**
 * 过滤HTML标签后截断字符串
 * @param type $str
 * @param type $len
 * @param type $suffix
 * @return type
 * @example short_text($data['Title'],12);
 * @since 1.0.0 2013-5-10 sutroon
 */
function short_text($str, $length = 12, $suffix = '...')
{
    $str = trim($str);
    $strlength = strlen($str);

    if ($length == 0 || $length >= $strlength)
    {
        return $str;  //截取长度等于0或大于等于本字符串的长度，返回字符串本身
    } elseif ($length < 0)
    {  //如果截取长度为负数
        $length = $strlength + $length; //那么截取长度就等于字符串长度减去截取长度
        if ($length < 0)
        {
            $length = $strlength; //如果截取长度的绝对值大于字符串本身长度，则截取长度取字符串本身的长度
        }
    }

    if (function_exists('mb_substr'))
    {
        $newstr = mb_substr($str, 0, $length, 'utf-8');
    } elseif (function_exists('iconv_substr'))
    {
        $newstr = iconv_substr($str, 0, $length, 'utf-8');
    } else
    {
        $newstr = substr($str, 0, $length);
    }

    if ($str != $newstr)
    {
        $newstr .= $suffix;
    }

    return $newstr;
}

/**
 * 获取随机字符串
 * 例：get_serialstring("A","/A","/a","/$yyMMdd","/0/6")
 * 前缀"/"表示变量,如：/a=随机小写字母;/A=随机大写字母;/0=随机数字;/Aa=随机大小写混合字母;/A0=随机大写和数字混合字母;/a0=随机小写和数字混合字母;/Aa0=随机大小写和数字混合字母
 * 变量长度定义在第二个"/"，如：/0/6=长度是6的随机数字;/a/3=长度是3的随机小写字母;
 * 时间变量加前缀"/$",如：/$yyMMdd={yyMMdd};
 * 没有前缀"/"表示固定字符串,如：A=A,A1=A1
 * 默认生成16位序列号，格式为：{A-1}{A-2}{0-1}{yyMMdd-6}{0-6},如：IAT0130129007536,JKT6130129107723,NNX0130129030138
 * 
 * @param array $formats
 * @return array
 * @example get_serialstring("A","/A","/a","/$yyMMdd","/0/6")
 * @since 1.0.0 2013-1-4 sutroon
 */
function get_serialstring($formats = array('/A', '/A/2', '/0', '/$Ymd', '/0/6'))
{
    $sb = '';
    $arr;
    $len;
    $fmt;
    $arrA = array(65, 91);
    $arra = array(97, 123);
    $arr0 = array(48, 58);
    $arrMy;
    foreach ($formats as $a)
    {
        if (!$a)
        {
            continue;
        }
        if (strlen($a) > 1 && substr($a, 0, 1) == '/')
        {
            $arr = explode('/', substr($a, 1));
            $fmt = $arr[0];
            if (substr($fmt, 0, 1) == '$')
            {
                $sb.=date(substr($fmt, 1));
                continue;
            }
            $len = 1;
            if (sizeof($arr) == 2)
            {
                $len = (int) $arr[1];
                if ($len < 1)
                    $len = 1;
            }
            switch ($fmt)
            {
                case 'A':
                    $arrMy = $arrA;
                    break;
                case 'a':
                    $arrMy = $arra;
                    break;
                case '0':
                    $arrMy = $arr0;
                    break;
                case 'Aa':
                    $arrMy = rand(0, 10) % 2 == 0 ? $arra : $arrA;
                    break;
                case 'A0':
                    $arrMy = rand(0, 10) % 2 == 0 ? $arr0 : $arrA;
                    break;
                case 'a0':
                    $arrMy = rand(0, 10) % 2 == 0 ? $arr0 : $arra;
                    break;
                default:
                    $arrMy = rand(0, 10) % 2 == 0 ? $arr0 : $arra;
                    if (rand(0, 100) % 3 == 0)
                    {
                        $arrMy = $arrA;
                    }
                    break;
            }
            for ($i = 0; $i < $len; $i++)
            {
                $sb.=chr(rand($arrMy[0], $arrMy[1] - 1));
            }
        } else
        {
            $sb.=$a;
        }
    }
    return $sb;
}

/**
 * 时间轴开发，即显示为“刚刚”、“5分钟前”、“昨天10:23”等
 * @param type $time
 * @return type
 * @example tran_time('2013-5-4 13:23:33');
 * @since 1.0.0 2013-5-4 sutroon
 */
function tran_time($time)
{
    if (!is_numeric($time))
    {
        $time = strtotime($time);
    }
    $rtime = date("m-d H:i", $time);
    $htime = date("H:i", $time);
    $time = time() - $time;
    if ($time < 60)
    {
        $str = '刚刚';
    } elseif ($time < 60 * 60)
    {
        $min = floor($time / 60);
        $str = $min . '分钟前';
    } elseif ($time < 60 * 60 * 24)
    {
        $h = floor($time / (60 * 60));
        $str = $h . '小时前 ' . $htime;
    } elseif ($time < 60 * 60 * 24 * 3)
    {
        $d = floor($time / (60 * 60 * 24));
        if ($d == 1)
        {
            $str = '昨天 ' . $rtime;
        } else
        {
            $str = '前天 ' . $rtime;
        }
    } else
    {
        $str = $rtime;
    }
    return $str;
}

/**
 * 增加时间
 * @param type $str
 * @param type $time
 * @return type
 * @example addtime('3 years');
 *      addtime('-3 years',date('Y-m-d H:i:s'));
 *      addtime('3 years',$data['CreatedTime']);
 * @since 1.0.0 2013-5-23 sutroon
 */
function addtime($str, $time = '')
{
    return date('Y-m-d H:i:s', $time ? strtotime($str, strtotime($time)) : strtotime($str));
}

/**
 * 安全地获取数组的值
 * @param type $data
 * @param type $name
 * @param type $defv
 * @return type
 * @since 1.0.0 2013-10-5
 * @example get_array_value($data,'Title');
 */
function get_array_value($data, $name, $defv = '')
{
    return is_array($data) && isset($data[$name]) ? $data[$name] : $defv;
}

/**
 * cookie计数器
 * 
 * 用在密码错误次数超过3次禁止登录等
 * 如：$n=cookietimer('loginn');
 *  if($n>2){
 *          die('您已尝试3次，请3分钟后再登录');	
 *  }else{
 *          redirect($msg.',还可以尝试'.(3-$n).'次','?m=Login&r=fail');	
 *  }
 * @param type $name
 * @param type $timer
 * @return type
 * @since 2013-9-25 by sutroon
 */
function cookietimer($name, $timer = 180)
{
    $n = isset($_COOKIE[$name]) ? $_COOKIE[$name] : 0;
    $n++;
    ob_start();
    setcookie($name, $n, time() + $timer);
    return $n;
}

/**
 * 计数器跳转
 * 
 * 用于用户登录超过N次停止输出或者跳转
 * @param type $msg
 * @param type $id
 * @param type $url
 * @param type $msgdie
 * @param type $counter
 * @param type $timer
 * @since 1.0.0 2013-12-11 sutroon
 */
function timer_die_or_redirect($msg, $id, $url, $msgdie = '您已尝试3次，请3分钟后再操作...', $counter = 3, $timer = 180)
{
    $n = cookietimer('loginn');
    if ($n > 2)
    {
        die($msgdie);
    } else
    {
        redirect($msg . ',还可以尝试' . ($counter - $n) . '次', $url);
    }
}

/**
 * 上传文件
 * 返回文件的服务器路径名称 
 * 注意：必需设置表单属性：enctype="multipart/form-data"
 * @param type $name
 * @param type $folder
 * @param type $autoday
 * @param type $exts
 * @return string
 * @since 1.0.0 2013-5-10 sutroon
 */
function upload_file($name, $folder = '/Upload', $autoday = true, $exts = 'jpg,jpeg,gif,png')
{
    if (empty($_FILES))
    {
        return '';
    }
    $folder = trim($folder, '/') . '/';
    if ($autoday)
    {
        $folder.='day_' . date('ymd') . '/';
    }
    if (!is_dir($_SERVER['DOCUMENT_ROOT'] . '/' . $folder))
    {
        @mkdir($_SERVER['DOCUMENT_ROOT'] . '/' . $folder, 0777, true);
    }
    $fileParts = pathinfo($_FILES[$name]['name']);
    if (!is_array($fileParts) || sizeof($fileParts) < 3)
    {
        return '';
    }
    $newfilename = $folder . date("YmdHis") . mt_rand(10000, 99999) . '.' . $fileParts['extension'];
    $fileTypes = explode(',', $exts);
    if (!in_array($fileParts['extension'], $fileTypes))
    {
        return '';
    }
    move_uploaded_file($_FILES[$name]['tmp_name'], $_SERVER['DOCUMENT_ROOT'] . '/' . $newfilename);
    return $newfilename;
}

/**
 * 获取文件上传控件
 * 例如：echo get_file_input('Thumb','a.jpg');
 * 需要用$this->upload_file($name,$rel)取值
 * @param type $name
 * @param type $src
 * @return type
 * @since 1.0.0 2013-5-10 sutroon
 */
function get_file_input($name, $src)
{
    if (!$src)
    {
        return '<input type="file" name="' . $name . '" />';
    }
    return '<img src="' . $src . '" style="width:120px; height:120px;" /><a href="###" onclick="$(this).next().toggle();">[更改]</a><input type="file" name="' . $name . '" style="display:none;" />';
}

?>
